package com.sea.physical.controller;


import com.codecrane.core.util.PhysicalStatusEnum;
import com.sea.physical.entity.CreateDespatchPlan;
import com.sea.physical.entity.CreateDespatchSku;
import com.sea.physical.entity.CreatePlan;
import com.sea.physical.service.*;

import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.supply.entity.Receive;
import com.sea.supply.service.ReceiveService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * 清关
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/customs")
public class CreateCustomsController {
    @Autowired
    private CreateDespatchPlanService createDespatchService;
    @Autowired
    private PortService portService;
    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CreateDespatchSkuService createDespatchSkuService;
    @Autowired
    private ReceiveService receiveService;
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model,@RequestParam("status")Integer status) {
        model.addAttribute("status",status-1);
        return "/sea/physical/createCustoms/main";
    }

    /**
     * 修改状态
     *
     * @param model
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Model model,@RequestParam("id")Integer id,@RequestParam("createPlanStatus")Integer createPlanStatus) {
        model.addAttribute("id",id);
        model.addAttribute("createPlanStatus",createPlanStatus);
        return "/bbpk/physical/createCustoms/edit";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDespatchPlan createDespatchPlan) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<CreateDespatchPlan> list = createDespatchService.findByCnd(createDespatchPlan);
        PageInfo<CreateDespatchPlan> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @ResponseBody
    @RequestMapping("/receive")
    public AjaxReturn receive(@RequestParam("ids") Integer ids[],
                              @RequestParam("userRealname") String userRealname,
                              @RequestParam("receiveDate") String receiveDate) {
        AjaxReturn result = Ajax.fail().setMsg("批量收货失败！");
        try {
            for (Integer createId : ids) {
                CreatePlan createPlan = createPlanService.findById(createId);
                List<Receive> list = receiveService.findByPlanNo(createPlan.getCreatePlanNo());
                if (list.size() == 0) {
                    createDespatchSkuService.receive(createId, userRealname,receiveDate);
                } else {
                    return result.setMsg("柜号【" + createPlan.getCreatePlanNo() + "】存在收货记录,无法一键收获！");
                }
            }
            result.setOk(true).setMsg("批量收货成功！");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }


    /**
     * 保存
     * @param createPlan
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public AjaxReturn send(CreatePlan createPlan,
                           @RequestParam(value = "recordOperateDate",required = false,defaultValue = "")String recordOperateDate,
                           @RequestParam(value = "recordText",required = false,defaultValue = "")String recordText) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try {
            //修改状态
            createPlanService.updateStatus(createPlan.getCreatePlanStatus()+1,createPlan.getId());
            //更新操作记录
            recordService.save(createPlan.getId(),createPlan.getCreatePlanStatus()+1,recordText,recordOperateDate);
            result.setOk(true).setMsg("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 根据状态取别名
     * @param status
     * @return
     */
    public String contansStatus(Integer status){
        String contans = "";
        switch (status){
            case 3 :
                contans = "已发运";
                break;
            case 4 :
                contans = "已开船";
                break;
            case 5 :
                contans = "已清关";
                break;
            case 6 :
                contans = "已送货";
                break;
            case 7 :
                contans = "已入库";
                break;
        }
        return  contans;
    }

    /**
     * 导出当前数据
     * @param response
     * @param createDespatchPlan
     */
    @RequestMapping(value = "/exportFreight")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response,CreateDespatchPlan createDespatchPlan)
    {
        List<CreateDespatchPlan> list = createDespatchService.findByCnd(createDespatchPlan);
        String[] title = {
                "柜号","柜型","运输方式","目的仓库","期间","预估运费","预估关税","预估关税(RMB)","实际运费","实际关税","货代公司","开船时间","订舱费用"};
        String fileName = "关税运费报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "关税运费报表";
        String[][] content = new String[list.size()][13];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchPlan map = list.get(i);
            content[i][0] = map.getCreatePlanNo();
            content[i][1] = map.getCreatePlanCabinetName();
            content[i][2] = map.getCreatePlanTransport();
            content[i][3] = map.getDespatchStoreName();
            content[i][4] = map.getCreatePeriod();
            content[i][5] = map.getDespatchFreight()+"";
            content[i][6] = map.getCreateCustomTax()+"";
            content[i][7] = map.getCreateCustomTaxCny()+"";
            content[i][8] = map.getDespatchRealFreight()+"";
            content[i][9] = map.getCreateRealTax()+"";
            content[i][10] = map.getDespatchSupplier();
            content[i][11] = map.getBoatDate();
            content[i][12] = map.getCreatePlanPrice()+"";
        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出当前数据
     * @param response
     * @param ids
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestParam("ids") Integer ids[])
    {
        List<CreateDespatchSku> list = createDespatchSkuService.getRows(ids);
        String[] title = {
                "柜号","装柜时间","shipment ID","渠道","SKU","产品名称","颜色","尺码(CM)","尺码(INCH)","FNSKU","Listing",
                "数量", "装箱量","箱数","内含件数","总件数","供应商","总毛重","总净重","总体积",
                "申报金额","清关金额","预估税金","预估运费","PO号","含税价","不含税价","出运港","目的港","目的港仓库","仓库","状态"};

        String fileName = "发运报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "发运报表";
        String[][] content = new String[list.size()][32];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchSku map = list.get(i);
            content[i][0] = map.getCreatePlanNo();
            content[i][1] = map.getCreatePlanPlaceDate();
            content[i][2] = map.getCreateShipmentId();
            content[i][3] = map.getCreateChannelName();
            content[i][4] = map.getCreateSku();
            content[i][5] = map.getProductName();
            content[i][6] = map.getProductColorName();
            content[i][7] = map.getProductCm();
            content[i][8] = map.getProductInch();

            content[i][9] = map.getCreateFnSku();
            content[i][10] = map.getCreateListing();
            content[i][11] = map.getCreateNumber().toString();


            content[i][12] = map.getCreatePackage().toString();
            content[i][13] = map.getCreateBoxNumber().toString();
            content[i][14] = map.getProductContainCount().toString();
            content[i][15] = map.getCreateNumberTotal().toString();
            content[i][16] = map.getCreateSupplierName();
            content[i][17] = map.getCreateWeightTotal().toString();
            content[i][18] = map.getCreateKgTotal().toString();
            content[i][19] = map.getCreateVolumeTotal().toString();
            content[i][20] = map.getCreateMoney().toString();
            content[i][21] = map.getCreateCustomMoney().toString();
            content[i][22] = map.getCreateCustomTax().toString();
            content[i][23] = map.getCreateCustomFreight().toString();
            content[i][24] = map.getErpProducePo().toString();
            content[i][25] = map.getErpProducePrice().toString();
            content[i][26] = map.getErpProduceUnitPrice().toString();
            content[i][27] = map.getDespatchPortName();
            content[i][28] = map.getDespatchDestName();
            content[i][29] = map.getDespatchStoreName();
            content[i][30] = map.getCreateWareName();
            content[i][31] = PhysicalStatusEnum.getStatusName(Integer.parseInt(map.getCreatePlanStatus()));
        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
